package org.mozhu.simple.rpc.server.network;

import java.nio.ByteBuffer;

public class RequestOrResponseSend extends NetworkSend {
    public RequestOrResponseSend(String destination, ByteBuffer buffer) {
        super(destination, buffer);
    }

    public RequestOrResponseSend(String destination, RequestOrResponse requestOrResponse) {
        this(destination, serialize(requestOrResponse));
    }

    private static ByteBuffer serialize(RequestOrResponse request) {
        int requestIdBytes = request.getRequestId().isPresent() ? 0 : 2;
        ByteBuffer buffer = ByteBuffer.allocate(request.sizeInBytes() + requestIdBytes);
        request.getRequestId().ifPresent(id -> buffer.putShort(id));
        request.writeTo(buffer);
        buffer.rewind();
        return buffer;
    }
}
